<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>盘点管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>盘点</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px">
							<select id="keyword01" name="keyword" lay-filter="keyword01">
								<option value="">请选择盘点类型</option>
								<option value="月盘点">月盘点</option>
								<option value="年盘点">年盘点</option>
								<option value="周盘点">周盘点</option>
								<option value="日盘点">日盘点</option>
							</select>
						</div>
					</td>

					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="selectState" name="selectState">
								<option value="">请选择</option>
								<option value="0">未盘点</option>
								<option value="1">已盘点</option>
								<option value="2">已复盘</option>
								<option value="3">已确认</option>
							</select>
						</div>
					</td>
					<td class="layui-input-inline">
						<input class="layui-input" id="startTime" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						-<input class="layui-input" id="endTime" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> 
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增盘点单</button>
			<button class="layui-btn layui-btn-danger" id="dels"><i class="layui-icon layui-icon-delete"></i>批量取消</button>
		<button class="layui-btn layui-btn-danger" id="restors"><i class="layui-icon layui-icon-delete"></i>批量恢复</button>
    
     <button class="layui-btn layui-btn-danger" id="export"><i class="layui-icon layui-icon-upload"></i>导出</button> </xblock>   </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	 <script type="text/html" id="rowToolbar">
        <a class="layui-btn layui-btn-xs" lay-event="confirm"><i class="layui-icon layui-icon-ok"></i>确认</a>
    </script>
	</div>
	
	<div id="subTable" class="x-body" hidden="hidden">
		<!-- <xblock>
			<button class="layui-btn layui-btn-danger" id="delete2"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
		</xblock> -->
		<input type="hidden"  id="orid"></input>
	  <table class="layui-hide" id="tableListSub" lay-filter="tableListSub"></table>
	</div>
	
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="detail"><i class="layui-icon layui-icon-edit"></i>盘点单详细调整</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del1"><i class="layui-icon layui-icon-delete"></i>删除</a>
	</script>
	<script type="text/html" id="rowToolbar2">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2">删除</a>
	</script>
	<script type="text/html" id="jyproductdiff">
 	 {{#  if(parseInt(d.difference_quantity) == 0){ }}
		<div style="background-color: #00BB00;">{{ d.difference_quantity }}</div>
  	 {{#  } if(parseInt(d.difference_quantity) < 0){ }}
    	<div style="background-color: #FF0000;">{{ d.difference_quantity }}</div>
  	 {{#  } if(parseInt(d.difference_quantity) > 0){ }}
    	<div style="background-color: #FFFF00;">{{ d.difference_quantity }}</div>
  	 {{#  } }}
	</script>
	
	<!-- 库位选择框 -->
	<div id="kwDiv" hidden="hidden" style="margin-bottom: 18px" class="x-body">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<input class="layui-input" name="location" id="location" placeholder="请输入库位或库区编号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<td>
						<input class="layui-input" name="materiel_num" id="materiel_num" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<td>
						<input class="layui-input" name="customer" id="customer" placeholder="请输入供应商名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload" id="ido" ><i class="layui-icon layui-icon-search"></i>检索</button>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform">提交</button>
		<div id="subDiv2">
			<table class="layui-hide" id="kwTable1" lay-filter="kwTable1"></table>
		</div>
	</div>
	
	<script type="text/javascript">
        var table;
        var orderStatus;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			//日期时间范围
	    	var minListDate = "1000-01-01 00:00:00";//最小可选时间，例：1990-02-01
	        var maxListDate = "3000-12-31 23:59:59";//最大可选时间，例：2200-12-31   
	        var enddate = laydate.render({
	            elem: "#endTime",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置结束时间 设置开始时间的最大值为结束时间
	                    begindate.config.max = {
	                        year: date.year,
	                        month: date.month - 1,//必须减1才是正确值
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除结束值    设置开始时间最大值
	                    var dateInit = new Date(maxListDate.replace(/-/g, "/"));
	                    begindate.config.max = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
	        var begindate = laydate.render({
	            elem: "#startTime",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置开始时间 设置结束时间的最小值为开始时间
	                    enddate.config.min = {
	                        year: date.year,
	                        month: date.month - 1,
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除开始值 ，设置结束值最小值
	                    var dateInit = new Date(minListDate.replace(/-/g, "/"));
	                    enddate.config.min = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
	        
		
		var $ = layui.jquery, active = {
			reload:function () {
				var keyword01 = $("#keyword01").val();
				var keyword02 = $("#selectState").val();
	            var keyword03 = "";
				
				var startTime = $.trim($("#startTime").val());
				if(startTime != null && startTime != ""){
					keyword03 = keyword03 + " and inventory_time >= '"+startTime+""+"' ";
				}
				var endTime = $.trim($("#endTime").val());
				if(endTime != null && endTime != ""){
					keyword03 = keyword03 + " and inventory_time <= '"+endTime+"' ";
				}
	              
				table.reload('contenttable',{
					method:'get',
					where:{	    keyword01:keyword01,
					    keyword02:keyword02,
					    keyword03:keyword03,
						}
					,page: {
	                    curr: 1//重新从第 1 页开始
	                }
				});
			}
		}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
		
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/inventory/queryInventoryOrderCriteria.do'
				,toolbar: '#toolbar'
				,title: 'machineList'
				,id :'contenttable'
				,limits:[10,20,30]
                //,defaultToolbar:['filter', 'print']
				,cols: [[
				  {type: 'checkbox', fixed: 'left', },
				  {field:'', title:'序号', width: 50,type:'numbers', align:'center'},
				  {field:'inventory_order_num', title:'盘点单号', align:'center'},
				  {field:'inventory_type', title:'盘点类型', align:'center'},
				  {field:'userName', title:'盘点人员', align:'center'},
				  {field:'inventory_time', title:'盘点日期', align:'center'
						,
                    	templet: function(d){
                    		return changeDateFormat(d.inventory_time)
                    }
					  },
				  {field:'checkedMan', title:'复盘人', align:'center'},
				  {field:'checked_time', title:'复盘日期', align:'center'},
				  {field:'confirmedMan', title:'确认人', align:'center'},
				  {field:'confirmed_time', title:'确认日期', align:'center'
					  ,
                  	templet: function(d){
                  		return changeDateFormat(d.confirmed_time)
                  }},
				  {field:'tab', title:'状态', align:'center', templet: function (row){
   	                    if (row.tab == 0) {
   	                        return "未盘点";
   	                    }else if(row.tab == 1){
   	                        return "已盘点";
   	                    }else if(row.tab == 2){
   	                        return "已复盘";
   	                    }else if(row.tab == 3){
   	                        return "已确认";
   	                    }
   	                }},
   	              {field: 'flag',title: '是否取消',align:'center' ,
                    	templet: function(d){
                        var value = d.flag;
                        if(value == 0){
                            value = "已取消"
                        }else if(value == 1){
                            value = "已恢复"
                        }else if(value == 2){
                            value = "未操作"
                        }
                        return value;
                    }},/*
                    {field: 'cancellation',title: '取消人',align:'center'},
                    {field: 'cancellation_time',title: '取消时间',align:'center'
                    	 ,
                       	templet: function(d){
                       		return changeDateFormat(d.cancellation_time)
                       }},
                    {field: 'restorer',title: '恢复人',align:'center'},
                    {field: 'restorer_time',title: '恢复时间',align:'center'
                    	 ,
                       	templet: function(d){
                       		return changeDateFormat(d.restorer_time)
                       }}, */
                   // {field: 'remark',title: '备注',align:'center'},
   	             ,{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:80, align: 'center'}
				]]
				,page: true
                ,done : function(){
                    $(".timepicker").each(function () {
                        laydate.render({
                            elem: this,
                            format: "yyyy-MM-dd"
                        });
                    });
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
			});
			
			//行内按钮点击事件
			table.on('tool(tableList)', function(obj){
	            var data = obj.data;
	            if(data.tab == 0) {
	            	toastr.warning("未盘点，不能确认！")
	            }else if( data.tab == 3) {
	            	toastr.warning("已确认，请勿重复操作！")
	            }else {
	            	layer.confirm('确定确认吗？确认后有差异的条码将进入损溢区', function(index){
		            	 $.ajax({
		                     type: "post",
		                     url: "${pageContext.request.contextPath }/inventory/confirm.do",
		                     data: { id:data.id},
		                     success: function(result){
		                     	toastr.success("确认完成！");
		                     	setTimeout(function(){
                                    location.reload();
                                },1000);
		                     }
		                 });
	            	});
	            }
			});
			
			//行单击事件
			table.on('row(tableList)', function(obj) {
				$("#subTable").show();
               	var data = obj.data;
               //	console.log(data.id);
               	$("#orid").val(data.id);
               	orderStatus = data.tab;
				if(data.checkedMan == ""){
	                table.render({
	                	elem: '#tableListSub'
	                   ,url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailCriteriaById.do?keyword01='+data.id
	                   ,toolbar: '#toolbar'
	                   ,title: 'machineList'
	                   ,id :'contenttable1'
	                   ,limits:[10,20,30]
	                  //,defaultToolbar:['filter', 'print']
	                   	,cols: [[
	                       	{type: 'checkbox', fixed: 'left'},
	                       	{field:'id1', title:'序号', width: 100, fixed: 'left', unresize: true, sort: true, type:'numbers'},
	                       	{field:'id', title:'ID', align:'center', hide:true}, //隐藏不显示
	                      	/*  {field:'customer_id', title:'供应商ID', align:'center', hide:true}, //隐藏不显示
	                       	{field:'customer_name', title:'供应商名称', align:'center'}, //隐藏不显示
	                       	{field:'region_name', title:'库区名称', align:'center'}, //隐藏不显
	                       	{field:'materiel_id', title:'物料ID', align:'center', hide:true}, //隐藏不显示
	                       	{field:'materiel_name', title:'物料名称', align:'center'},
	                       	{field:'materiel_num', title:'物料编号', align:'center'},
	                       	{field:'materiel_size', title:'物料规格', align:'center'},
	                       	{field:'materiel_properties', title:'物料型号', align:'center'},
	                       	{field:'unit', title:'单位', align:'center'}, */
						   	{field:'location_num', title:'库位编号', align:'center', event: 'collapse',
   								templet: function(d) {
       								return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.location_num + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
       						}},
						   	{field:'theoretical_quantity', title:'库存数量', align:'center'},
	                       	{field:'actual_quantity', title:'初盘数量', align:'center', edit: false, templet: function (row){
								return '<span>'+row.actual_quantity+'</span>';
							}},
							{field:'difference_quantity', title:'初盘差异', align:'center'},
		                   ]]
		                   ,page: true
		                   ,done : function(){
		                       $('th').css({
		                           'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                       })
		                   }
		               });
	               }else{
		                table.render({
		                	elem: '#tableListSub'
		                   ,url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailCriteriaById.do?keyword01='+data.id
		                   ,toolbar: '#toolbar'
		                   ,title: 'machineList'
		                   ,id :'contenttable1'
		                   ,limits:[10,20,30]
		                   ,defaultToolbar:['filter', 'print']
		                   ,cols: [[
		                	   	{type: 'checkbox', fixed: 'left'},
		                       	{field:'id1', title:'序号', width: 100, fixed: 'left', unresize: true, sort: true, type:'numbers'},
		                       	{field:'id', title:'ID', align:'center', hide:true}, //隐藏不显示
		                       	{field:'location_num', title:'库位编号', align:'center', event: 'collapse',
	   								templet: function(d) {
	       								return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.location_num + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
	       						}},
							   	{field:'theoretical_quantity', title:'库存数量', align:'center'},
		                       	{field:'actual_quantity', title:'初盘数量', align:'center', edit: false, templet: function (row){
									return '<span>'+row.actual_quantity+'</span>';
								}},
								{field:'difference_quantity', title:'初盘差异', align:'center'},
								{field:'check_num', title:'复盘数量', align:'center'},
								{field:'check_diff', title:'复盘差异', align:'center'},
		                   	]]
		                   ,page: true
		                   ,done : function(){
		                       $('th').css({
		                           'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                       })
		                   }
		               });
					} 
           });
			
			//"出库单详细"的行内展开事件
            table.on('tool(tableListSub)', function(obj){
            	//展开详细表的下表效果
            	if (obj.event === 'collapse') {
    				var trObj = layui.$(this).parent('tr'); //当前行
    				var accordion = true //开启手风琴，那么在进行折叠操作时，始终只会展现当前展开的表格。
    				var content = '<table></table>' //内容
    				//表格行折叠方法
    				collapseTable({
    					elem: trObj,
    					accordion: accordion,
    					content: content,
    					success: function (trObjChildren, index) { //成功回调函数
    						//trObjChildren 展开tr层DOM
    						//index 当前层索引
    						trObjChildren.find('table').attr("id", index);
                            /*===================================start===================================*/
    						table.render({
    							elem: "#" + index
                                ,url:'${pageContext.request.contextPath }/inventory/queryCodeListByinvenId.do?invenId=' + obj.data.id
                                ,title: 'machineList'
                                ,cols:
    								[[
                                        {field:'id',title:'序号',sort: true,width: 60,type:'numbers',align:'center'},
                                        {field: 'code',title: '条码',align:'center'},
                                        {field: 'theory_num',title: '库存',align:'center', templet: function(d){
    										if(d.theory_num == 0){
    											return 0;
    										} else {
    											return d.theory_num;
    										}
    									}},
                                        {field: 'reality_num',title: '实际',align:'center', templet: function(d){
    										if(d.reality_num == 0){
    											return 0;
    										} else {
    											return d.reality_num;
    										}
    									}},
                                        {field: 'diff_num',title: '差异',align:'center', templet: function(d){
    										if(d.diff_num == 0){
    											return 0;
    										} else {
    											return d.diff_num;
    										}
    									}},
    									{field: 'location_num',title: '状态',align:'center', templet: function(d){
    										if(d.location_num == 1){
    											return "已抹平";
    										} else {
    											return "未抹平";
    										}
    									}},
                                    ]]
                                ,page: false
    						});
    						/*===================================end===================================*/
    					}
    				});
    			}
            });
			
            table.render({
	             elem: '#kwTable1'
	             ,url:'${pageContext.request.contextPath }/inventory/selectLocation.do?'
	             //,limits:[10,20,30]
	             //,defaultToolbar:['filter', 'print']
	             ,cols: [[
						{type: 'checkbox', fixed: 'left'}
						,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
						,{field:'location_num', title:'库位'}
					]]
	             ,page: false
	              ,done : function(){
	                 $('th').css({
	                     'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                 })
	             } 
	         });
			
		var ids =new Array();
        //当前表格中的全部数据:在表格的checkbox全选的时候没有得到数据, 因此用全局存放变量
        var table_data=new Array()
		table.on('checkbox(materielTable)', function (obj) {
           if(obj.checked==true){
               if(obj.type=='one'){
                   ids.push(obj.data.id);
              }else{
                   for(var i=0;i<table_data.length;i++){
                       ids.push(table_data[i].id);
                   }
               }
           }else{
               if(obj.type=='one'){
                   for(var i=0;i<ids.length;i++){
                      if(ids[i]==obj.data.id){
                           ids.remove(i);
                       }
                  }
               }else{
                   for(var i=0;i<ids.length;i++){
                       for(var j=0;j<table_data.length;j++){
                           if(ids[i]==table_data[j].id){
                              ids.remove(i);
                          }
                       }
                   }
               }
           }
           for(var i=0;i<ids.length;i++){
           		//console.log("*******************"+ids[i].id)
           }
        });
            //"盘点单"的行内编辑事件
            table.on('edit(tableList)', function(obj){
                var fieldValue = obj.value, 		//得到修改后的值
                    rowData = obj.data, 			//得到所在行所有键值
                    fieldName = obj.field; 			//得到字段
                	layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath }/inventory/updateInventoryOrderById.do",
                        data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue, theoretical_quantity:rowData.theoretical_quantity},
                        success: function(data){
                        	toastr.success("修改成功！");
                            location.reload();
                        }
                    });
                });
            });

            //"盘点单详细"的行内编辑事件
            table.on('edit(tableListSub)', function(obj){
            	if(orderStatus == 0){
            		var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 
               		//得到字段
                	layui.use('jquery',function(){
	                    var $=layui.$;
	                    $.ajax({
	                        type: "post",
	                        url: "${pageContext.request.contextPath }/inventory/updateInventoryOrderDetailById.do",
	                        data: { mid:rowData.materiel_id, fieldName:fieldName, fieldValue:fieldValue,cid:rowData.customer_id ,detailid:rowData.id},
	                        success: function(data){
	                        	toastr.success("修改成功！");
	                            location.reload();
	                        }
	                    });
                	});
            	}else{
            		toastr.warning("已盘点，不能修改记录！")
            	}
            });

			/**
			 * 添加弹框中，选择物料后，点提交，带回的操作
			 */
			form.on('submit(productform)', function (data) {
				var checkStatus = table.checkStatus('kwTable1')
	      		var data = checkStatus.data;
				var b;
				for (var i = 0; i < data.length; i++) {
					console.log("************"+data[i].location_num)
				 	
                   	var val01 = data[i].location_num == null?"":data[i].location_num;
                   	
                   	$("#myTable").find("tr").each(function(){
                    	var tdArr = $(this).children();
                       	var h = tdArr.eq(0).text();
                       	if(h==val01){
                       		b=0;
                        }
                 	})
				 }
                 if(b!=0){
              		var checkStatus = table.checkStatus('kwTable1')
  		      		var data = checkStatus.data;
  					 for (var i = 0; i < data.length; i++) {
  						 console.log("************"+data[i].location_num)
  						 var val01 = data[i].location_num == null?"":data[i].location_num;
  							$("#myTable tbody").append('<tr >'+
  								'<td>'+val01+'</td>'+
  							'</tr>');
  						}
  		            layer.close(productIndex)
  					return false;
                 }else{
              	  //toastrStyle();
              	  //toastr.warning("记录已经存在，不能重复添加")
              	  layer.msg("记录已经存在，不能重复添加");
  				 return false;
              	 }
	        });
			
			 $(document).on('click','#btn',function(){
				 productIndex= layer.open({
		                type: 1 					//Page层类型
		                ,area: ['900px', '650px'] 	//宽  高
		                ,title: '库位清单'
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: $("#kwDiv")
		                ,success: function () {
		                	 var location=$('#location').val("");
		    				 var materiel_num=$('#materiel_num').val("");
		    				 var customer=$('#customer').val("");
		                   
		                }
		            });
			 });
			 
			 $(document).on('click','#ido',function(){
				 var location=$('#location').val().trim();
				 var materiel_num=$('#materiel_num').val().trim();
				 var customer=$('#customer').val().trim();
				 var verify = /^[0-9,-]*$/;
				 
				 if(verify.test(materiel_num)){
				 split = materiel_num.split(',')
					 if(split.length <= 5){
					    var table = layui.table;
				        table.reload('kwTable1', {
				            method:'post',
				            where:{
				            	"location":location
				                ,"materiel_num":materiel_num
				                ,"customer":customer
				            },
				            done:function (res) {
			            	  $('th').css({
	                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                            })
				            }
				        });
					 }else{
	    				layer.msg("最多可同时查5个！");
	    			 }
				 }else{
	    			layer.msg("只能输入数字和英文逗号！");
	    		} 
			 });
	
	
		
		
			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/inventory/addInventoryOrder.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
				}).done(
					function(res) {
						if (res > 0) {
							var idArr = new Array();
							idArr[0] = res;
							var tabLength = $("#tbody").find("tr").length ;
							if(tabLength == 0){
								$.ajax({
	                                type:'post'
	                                ,url:'${pageContext.request.contextPath}/inventory/deleteInventoryOrderById.do'
	                                ,data:{"idArr":idArr}
	                                ,dataType:'json'
	                                ,success:function(data){
	                                	
	                                }
	                            })
                               	toastrStyle();
   								toastr.error('新增失败，请选择盘点的物料');
							}else{
								//console.log("**"+res);
								//如果父表新增成功再执行新增子表的操作
								$("#tbody tr").each(function(i,dom){
		                            var tr = $(dom).closest("tr");
		                            var tds = tr.find("td");
		                            //主表插入行ID
		                            var order_id = res;
		                            var location_num = tds.eq(0).html();
		                            $.ajax({
		                                type:'post'
		                                ,url:'${pageContext.request.contextPath}/inventory/addInventoryOrderDetail.do'
		                                ,data:{order_id:order_id,location_num:location_num}
		                                ,dataType:'json'
		                                ,success:function(data){
		                                    //console.log(data);
		                                }
		                            })
	                        	});
								/* —————————————— */
								toastrStyle();
								toastr.success('新增成功！');
								setTimeout(function(){
									location.reload();
								},1000);
								/* —————————————— */
							}
						}
					}
				).fail(
					function(res) {
						toastrStyle();
						toastr.error('新增失败！');
						setTimeout(function(){
							location.reload();
						},1000);
					}
				)
				return false;
			});

			/**
			 * 新增表单校验
			 */
			form.verify({
				//value：表单的值item：表单的DOM对象
				inventory_type: function(value, item){
					if(value == ''){
						return '盘点类型不能为空';
					}
				},
				
			});
			$("#dels1").click(function(){
				if(orderStatus == 0){
					var rowData = table.checkStatus('contenttable1');
					var data = rowData.data;
					var idArr = new Array();
					if(data.length == 0){
						toastrStyle();
						toastr.warning("请至少选择一条记录！");
					} else {
						for(var i=0;i < data.length;i++){
							idArr[i] = data[i].id;
						}
						layer.confirm('确定删除吗？', function(index){
							$.ajax({
								type:'post',
								url:'${pageContext.request.contextPath }/inventory/deleteInventoryOrderDetailById.do',
								data:{"idArr" : idArr},
								success:function(data){
									if(data > 0){
										toastrStyle();
										toastr.success("删除成功！");
										setTimeout(function(){
											location.reload();
										},1000);
										setTimeout(function(){
											window.location.reload();
										},2000);
									}else{
										toastrStyle();
										toastr.warning("删除失败！");
										location.reload();
									}
								}
							});
						});
					}
				}else{
					toastr.warning("已盘点，不能修改记录！")
				}
				
			});
			//新增
            $("#add").click(function(){
            	//时间戳
        		var timestamp = (new Date()).getTime();
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1000px', '500px'] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content:
                        '<div id="addDivID">'+
							'<form class="layui-form" id="addFormID">'+
								'<xblock>'+
									'<table>'+
										'<tr>'+
											'<td><label class="layui-form-label">盘点单号</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="inventory_order_num" name="inventory_order_num" value="PDDH-'+timestamp+'" style="width: 190px; color: gray">'+
											'</td>'+
											'<td><label class="layui-form-label">盘点类型</label></td>'+
											'<td style="width:250px">'+
												'<div style="width: 190px; float: left;">' +
													'<select id="inventory_type" name="inventory_type" lay-verify="inventory_type" lay-filter="inventory_type" style="width: 190px">' +
														'<option value="">请选择盘点类型</option>' +
														'<option value="日盘点">日盘点</option>' +
														'<option value="周盘点">周盘点</option>' +
														'<option value="月盘点">月盘点</option>' +
														'<option value="年盘点">年盘点</option>' +
													'</select>'+
												'</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
											'<td>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;</td>'+
											'<td>'+
			                                    '<button type="button" class="layui-btn" id="btn">请选择盘点的库位</button>'+
											'</td>'+
										'</tr>'+
									'</table>'+
								'</xblock>'+
								
								'<table class="layui-table" id="myTable">' +
									'<thead style="text-align: center">'+
										'<tr style="background: #009688; color: white; align: center" >'+
											'<th style="text-align:left;">库位编号</th>'+
										'</tr>'+
									'</thead>'+
									'<tbody id="tbody" style="text-align: left;">'+
	                    			'</tbody>'+
								'</table>'+
								'<xblock>'+
									'<button class="layui-btn layui-btn-blue" lay-submit lay-filter="addForm" style="margin-left:360px; margin-bottom: 10px">提交</button>'+
									'&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>'+
								'</xblock>'+
								'</table>'+
							'</form>'+
                    	'</div>'
                    ,success: function(){
                        laydate.render({
                            elem: '#inventory_time1'
                        });
                        form.render();
                    }
                });
			});

          //批量删除
			$("#dels").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					var sum = 0;
					for(var i=0;i < data.length;i++){
						if(data[i].tab != 0){
							sum += 1;
						}if(data[i].flag == 0){
	                        toastr.warning("对不起，已取消的数据不能取消！");
	                        return;
	                    }
					}
					if(sum == 0){
						for(var i=0;i < data.length;i++){
							idArr[i] = data[i].id;
						}
						layer.confirm('确定取消吗？', function(index){
							$.ajax({
								type:'post',
								url:'${pageContext.request.contextPath }/inventory/deleteInventoryOrderById.do',
								data:{"idArr" : idArr},
								success:function(data){
									if(data > 0){
										toastrStyle();
										toastr.success("取消成功！");
										setTimeout(function(){
											location.reload();
										},1000);
										setTimeout(function(){
											window.location.reload();
										},2000);
									}else{
										toastrStyle();
										toastr.warning("取消失败！");
										location.reload();
									}
								}
							});
						});
					}else{
						toastr.warning("不能取消已盘点记录！")
					}
				}
			});
	        $("#export").click(function(){
	        	var keyword01 = $("#keyword01").val();
				var selectState = $("#selectState").val();
	            window.location.href="${pageContext.request.contextPath}/inventory/doExportall.do?keyword01="+keyword01+"&keyword02="+selectState;
	        })
			$("#restors").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					var sum = 0;
					for(var i=0;i < data.length;i++){
						if(data[i].tab != 0){
							sum += 1;
						}if(data[i].flag == 1){
	                        toastr.warning("对不起，已恢复的数据不能恢复！");
	                        return;
	                    }
					}
					if(sum == 0){
						for(var i=0;i < data.length;i++){
							idArr[i] = data[i].id;
						}
						layer.confirm('确定恢复吗？', function(index){
							$.ajax({
								type:'post',
								url:'${pageContext.request.contextPath }/inventory/restor.do',
								data:{"idArr" : idArr},
								success:function(data){
									if(data > 0){
										toastrStyle();
										toastr.success("恢复成功！");
										setTimeout(function(){
											location.reload();
										},1000);
										setTimeout(function(){
											window.location.reload();
										},2000);
									}else{
										toastrStyle();
										toastr.warning("恢复失败！");
										location.reload();
									}
								}
							});
						});
					}else{
						toastr.warning("不能恢复已盘点记录！")
					}
				}
			});
			
		
			
		
			
			form.on('select(inventory_warehouse)', function(data){
		    	var id = data.value;	//改变后的值
		    	//根据仓库ID获取供应商信息
		    	$.ajax({
	                type: "post",
	                url: "${pageContext.request.contextPath }/cancellingStockManager/getCustomerByWarehouseId.do",
	                data:{"id":id},
	                dataType: 'JSON',
	                async: false,
	                success: function (datas) {
	                	//设置下拉列表中的值的属性
	                    for ( var i = 0; i < datas.length; i++) {
	                    	//增加下拉列表。
	                      	$("#customer_id").append("<option value='"+datas[i].id+"'>"+datas[i].customer_name+"</option>");
	        			}
	                }
	          	});
				form.render();
		    });
			//完毕
			})
		//获取选中产品清单
		 function changeDateFormat(timestamp) {
    	if (timestamp == '') {
			return '';
		} else {
			var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			Y = date.getFullYear() + '-';
			M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
			D = (date.getDate()+1 < 10 ? '0'+(date.getDate()) : date.getDate())+ '      ';
			H = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())+ ':';
            MI= (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())+':';
            S = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
				
				return Y+M+D+H+MI+S;
		
		}
    }
		function addProduct (){
            var wareId = $('#inventory_warehouse').val();
            var customerId = $('#customer_id').val();
			layer.open({
                type: 1 					//Page层类型
                ,area: ['900px', '450px'] 	//宽  高
                ,title: '产品清单'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: '<form class="layui-form">' +
							   	'<table id="productTable" lay-filter="productTable"></table>' +
						  '</form>'
                ,success: function () {
                    table.render({
                        elem: '#productTable'
                        ,url:'${pageContext.request.contextPath }/cancellingStockDetailManager/listPageMaterielByWarehouseId.do?warehouseId='+wareId+'&customerId'+customerId
                        ,limits:[10,20,30]
                        ,defaultToolbar:['filter', 'print']
                        ,cols: [[
           					{type: 'checkbox', fixed: 'left'}
           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
           					,{field:'materiel_name', title:'物料名称',templet:function(row){
           						if(row.materiel_name!=null){
           							return row.materiel_name;
           						}else{
           							return "";
           						}
           					}}
           					,{field:'materiel_num', title:'产品码',templet:function(row){
           						if(row.materiel_num!=null){
           							return row.materiel_num;
           						}else{
           							return "";
           						}
           					}}
           					,{field:'brevity_num', title:'简码',templet:function(row){
           						if(row.brevity_num!=null){
           							return row.brevity_num;
           						}else{
           							return "";
           						}
           					}}
           				]]
                        ,page: true
                        ,done : function(){
                            $('th').css({
                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                            });
                        }
                    });
                }
            }); 
		}
     //日期格式转换
        function dateToStr(date) {
            var time = new Date(date.time);
            var y = time.getFullYear();
            var M = time.getMonth() + 1;
            M = M < 10 ? ("0" + M) : M;
            var d = time.getDate();
            d = d < 10 ? ("0" + d) : d;
            var str = y + "-" + M + "-" + d;
            return str;
        }
        
      	//日期格式转换
		function date2String(timestamp){
			var d = new Date(timestamp);
			var date = (d.getFullYear()) + "-" + 
		       (d.getMonth() + 1<10?"0"+(d.getMonth() + 1):d.getMonth() + 1) + "-" +
		       (d.getDate()<10?"0"+d.getDate():d.getDate());
			return date;
		}
      	
		function formatDate(time) { 
			var d = new Date(time);
        	var dformat = [ d.getFullYear(),
        	checkTime(d.getMonth() + 1), checkTime(d.getDate()) ].join('-');
        	return dformat;
    	};
    	
   	  	//修改时间戳查询时间
		function checkTime(n) {
			return n < 10 ? '0' + n : n;
   	  	};
   	  	
   	//表格行折叠方法
        function collapseTable(options) {
            var trObj = options.elem;
            if (!trObj) {
                return;
            }
            var accordion = options.accordion,
                success = options.success,
                content = options.content || '';
            var tableView = trObj.parents('.layui-table-view'); //当前表格视图
            var id = tableView.attr('lay-id'); //当前表格标识
            var index = trObj.data('index'); //当前行索引
            var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
            var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
            var colspan = trObj.find('td').length; //获取合并长度
            var trObjChildren = trObj.next(); //展开行Dom
            var indexChildren = id + '-' + index + '-children'; //展开行索引
            var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
            var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
            var lw = leftTr.width() + 15; //左宽
            var rw = rightTr.width() + 15; //右宽
            //不存在就创建展开行
            if (trObjChildren.data('index') != indexChildren) {
                //装载HTML元素
                var tr = '<tr data-index="' + indexChildren + '"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
                trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
                var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
                leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
                rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
            }
            //展开|折叠箭头图标
            trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
            //显示|隐藏展开行
            trObjChildren.toggle();
            //开启手风琴折叠和折叠箭头
            if (accordion) {
                trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
                trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
                rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
                leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
            }
            success(trObjChildren, indexChildren); //回调函数
            heightChildren = trObjChildren.height(); //展开高度固定
            rightTrChildren.height(heightChildren + 115).toggle(); //左固定
            leftTrChildren.height(heightChildren + 115).toggle(); //右固定
        }
   		 toastrStyle();
	</script>
</body>
</html>
